package com.ruoyi.creditlife.service.impl;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.creditlife.domain.BookBorrowTracking;
import com.ruoyi.creditlife.domain.BookBorrrowRecord;
import com.ruoyi.creditlife.domain.BookInfo;
import com.ruoyi.creditlife.domain.CreditLifeBehavior;
import com.ruoyi.creditlife.mapper.BookBorrowTrackingMapper;
import com.ruoyi.creditlife.mapper.BookBorrrowRecordMapper;
import com.ruoyi.creditlife.mapper.BookInfoMapper;
import com.ruoyi.creditlife.mapper.CreditLifeBehaviorMapper;
import com.ruoyi.creditlife.service.IBookBorrrowRecordService;
import com.ruoyi.creditlife.service.ICreditLifeBehaviorService;
import com.ruoyi.creditlife.service.util.CaculateAmount;
import com.ruoyi.system.domain.CreditUserInfo;
import com.ruoyi.system.mapper.CreditUserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BookBorrrowRecordServiceImpl implements IBookBorrrowRecordService
{
    @Resource
    private BookBorrrowRecordMapper bookBorrrowRecordMapper;

    @Resource
    private CreditLifeBehaviorMapper creditLifeBehaviorMapper;

    @Resource
    private BookBorrowTrackingMapper bookBorrowTrackingMapper;

    @Resource
    private BookInfoMapper bookInfoMapper;

    @Resource
    private CaculateAmount caculateAmount;

    @Resource
    private ICreditLifeBehaviorService creditLifeBehaviorService;

    @Resource
    private CreditUserInfoMapper creditUserInfoMapper;

    @Override
    public BookBorrrowRecord selectBookBorrrowRecordById(Long id) {
        return bookBorrrowRecordMapper.selectBookBorrrowRecordById(id);
    }

    @Override
    public List<BookBorrrowRecord> selectBookBorrrowRecordList(BookBorrrowRecord bookBorrrowRecord) {
        return bookBorrrowRecordMapper.selectBookBorrrowRecordList(bookBorrrowRecord);
    }

    @Override
    public int insertBookBorrrowRecord(BookBorrrowRecord bookBorrrowRecord) {
        return bookBorrrowRecordMapper.insertBookBorrrowRecord(bookBorrrowRecord);
    }

    @Override
    public int updateBookBorrrowRecord(BookBorrrowRecord bookBorrrowRecord) {
        return bookBorrrowRecordMapper.updateBookBorrrowRecord(bookBorrrowRecord);
    }

    @Override
    public int deleteBookBorrrowRecordByIds(Long[] ids) {
        return bookBorrrowRecordMapper.deleteBookBorrrowRecordByIds(ids);
    }

    @Override
    public int deleteBookBorrrowRecordById(Long id) {
        return bookBorrrowRecordMapper.deleteBookBorrrowRecordById(id);
    }

    @Override
    public int userBorrrowBookRecord(Long bookid, Long lendtime) {
        BookBorrrowRecord borrrowRecord = new BookBorrrowRecord();
        borrrowRecord.setUserId(SecurityUtils.getUserId());
        borrrowRecord.setBookId(bookid);
        borrrowRecord.setBorrowTime(new Date());
        LocalDate borrowDate = LocalDate.now();
        LocalDate dueDate = borrowDate.plusDays(lendtime);
        Date dueTime = Date.from(dueDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        borrrowRecord.setDueTime(dueTime);
        borrrowRecord.setIsOverdue((long)1);
        // borrrowRecord.setAmount(BigDecimal.valueOf((long)0)); // 借阅金额，写死为0了
        BookInfo bookInfo = bookInfoMapper.selectBookInfoByBookId(bookid);
        BigDecimal amount = BigDecimal.ZERO;
        if (bookInfo != null) {
        // 这里举例：单价 * 借阅天数
        amount = bookInfo.getBookValue();
        }
        borrrowRecord.setAmount(amount);
        borrrowRecord.setCreditImpact((long)0);
        borrrowRecord.setStatus("未归还");

        int result = bookBorrrowRecordMapper.insertBookBorrrowRecord(borrrowRecord);

        CreditLifeBehavior creditLifeBehavior = new CreditLifeBehavior();
        creditLifeBehavior.setUserId(SecurityUtils.getUserId());
        creditLifeBehavior.setServiceType((long)2);
        creditLifeBehavior.setBehaviorType("借阅图书");
        creditLifeBehavior.setLocation("东北大学图书馆");
        creditLifeBehavior.setAmount(BigDecimal.valueOf(0));
        creditLifeBehavior.setStartTime(new Date());
        creditLifeBehavior.setStatus("进行中");
        creditLifeBehavior.setCreditImpact((long)0);
        creditLifeBehaviorMapper.insertCreditLifeBehavior(creditLifeBehavior);

        BookBorrowTracking bookBorrowTracking = new BookBorrowTracking();
        bookBorrowTracking.setBehaviorId(creditLifeBehavior.getId());
        bookBorrowTracking.setBorrowId(borrrowRecord.getId());
        bookBorrowTrackingMapper.insertBookBorrowTracking(bookBorrowTracking);

        return result;
    }

    @Override
    public int batchUpdateOverdueRecords() {
        List<BookBorrrowRecord> recordList = bookBorrrowRecordMapper.selectBookBorrrowRecordList(new BookBorrrowRecord());
        List<BookBorrrowRecord> overdueRecords = new ArrayList<>();
        LocalDate currentDate = LocalDate.now();

        for (BookBorrrowRecord item : recordList) {
            LocalDate dueDate = item.getDueTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            if (item.getDueTime() != null
                    && dueDate.isBefore(currentDate)
                    && !"已逾期".equals(item.getStatus())
                    && item.getReturnTime() == null) {

                item.setAmount(caculateAmount.calculateOverdueAmount(item));
                item.setCreditImpact((long)-4);

                BookBorrowTracking bookBorrowTracking = bookBorrowTrackingMapper.selectBookBorrowTrackingByBorrowId(item.getId());

                CreditLifeBehavior creditLifeBehavior = new CreditLifeBehavior();
                creditLifeBehavior.setId(bookBorrowTracking.getBehaviorId());
                creditLifeBehavior.setStatus("已逾期");
                creditLifeBehavior.setCreditImpact((long)-4);
                creditLifeBehavior.setAmount(caculateAmount.calculateOverdueAmount(item));
                creditLifeBehaviorMapper.updateCreditLifeBehavior(creditLifeBehavior);

                item.setIsOverdue((long)0);
                item.setStatus("已逾期");

                // 使用 CreditUserInfo 更新信用分
                CreditUserInfo userInfo = creditUserInfoMapper.selectCreditUserInfoByUserId(creditLifeBehavior.getUserId());
                if (userInfo != null) {
                    userInfo.setCreditScore(userInfo.getCreditScore() - 4);
                    creditUserInfoMapper.updateCreditUserInfo(userInfo);
                }

                overdueRecords.add(item);
            }
        }

        if (!overdueRecords.isEmpty()) {
            bookBorrrowRecordMapper.batchUpdateOverdueRecords(overdueRecords);
        }

        return 1;
    }
}